
class Layer {
    constructor(path, method, cb) {
        this.path = path
        this.method = method
        this.cb = cb
    }

    match(path, method) {
        return this.path === path && this.method === method.toLowerCase()
    }

}


class Router {
    constructor() {
        this.stack = []
    }
    compose(layers, ctx, next) {

        const dispatch = (i) => {
            if (i === layers.length) return next()
            let cb = layers[i].cb
            return Promise.resolve(cb(ctx, () => dispatch(i + 1)))
        }

        return dispatch(0)
    }

    routes() {
        return async (ctx, next) => {
            let layers = this.stack.filter(layer => layer.match(ctx.path, ctx.method))
            console.log(layers)

            this.compose(layers, ctx, next)
        }
    }
};

['get', 'post'].forEach((method) => {
    Router.prototype[method] = function (path, cb) {
        let layer = new Layer(path, method, cb)
        this.stack.push(layer)
    }
})

module.exports = Router